﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using OreSystem.Common;
namespace MainFrom
{
    public partial class FormRestoreDataBase : Form
    {
        public FormRestoreDataBase()
        {
            InitializeComponent();
        }

        private void btn_SelectBackFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                txt_BackFile.Text = ofd.FileName;
            }
        }

        private void btn_ResortDataBase_Click(object sender, EventArgs e)
        {
            string restoreDataBase = @"USE MASTER
ALTER DATABASE {0} SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE {0}
FROM DISK='{1}'
WITH REPLACE";

            string DataBaseName = string.Empty;
            string BackFile = string.Empty;
            if (string.IsNullOrEmpty(txt_BackFile.Text))
            {
                MessageBox.Show("没有选择备份文件");
                return;

            }
            BackFile = txt_BackFile.Text;
            if (comboBox3.SelectedItem == null)
            {
                MessageBox.Show("没有选择要还原的数据库");
            }
            DataBaseName = comboBox3.SelectedValue.ToString();
            if (!File.Exists(BackFile))
            {
                MessageBox.Show("备份文件不存在");
                return;
            }
            string sql = string.Format(restoreDataBase, DataBaseName, BackFile);
            try
            {
                MsSqlHelper.ExceuteNoQuery(sql, null);
                MessageBox.Show("数据库还原成功");
            }
            catch (Exception ex)
            {

                MessageBox.Show(ex.ToString());
            }
        }

        private void FormRestoreDataBase_Load(object sender, EventArgs e)
        {
            initDataBase();
        }
        public void initDataBase()
        {
            DataTable dt = MsSqlHelper.ExcuteQuery("select * from master.dbo.sysdatabases order by dbid desc", null);
            comboBox3.DataSource = dt;
            comboBox3.DisplayMember = "name";
            comboBox3.ValueMember = "name";
        }
    }
}
